package com.redtree.air.db
{
	

	public class Contacts extends Model
	{
		public function Contacts()
		{
			super();
			dataGridColumnsAry = [['name','姓名'],['content','联系方式'],['typeName','类型'],['deptName','部门'],['securityName','安全级别']];
			tableName = getTableName('contacts');
		}
		public function getContacts(offset:int=0,limit:int=DEFAULT_PAGE_SIZE,underSecurity:Boolean=true,justCurrentLevel:Boolean=false):Array
		{
			var sql:String = "select c.*,d.name as dept_name, ct.name as type_name, s.name as security_name " +
				"from contacts as c " +
				"left join contact_types as ct on ct.id=c.type_id " +
				"left join depts as d on c.dept_id=d.id " +
				"left join security as s on s.level_id=c.security_level";
			if( underSecurity )
				sql += " where c.security_level "+(justCurrentLevel?"=":"<=")+" "+currentSecurityLevel;
			if( limit )
				sql += " limit "+(limit)+" offset "+(offset-1)*limit;
			return _getContactsBySql(sql);

		}
		public function getLevelReferData(offset:int=0,limit:int=DEFAULT_PAGE_SIZE):Array
		{
			return getContacts(offset,limit,true,true);
		}
		public function getReferTotalCount():int
		{
			return getTotalCount(true,true);
		}
		public function getTotalCount(underSecurity:Boolean=true,justCurrentLevel:Boolean=false):int{
			var sql:String = "select count(*) as num from contacts as c";
			if( underSecurity )
				sql += " where c.security_level "+(justCurrentLevel?"=":"<=")+" "+currentSecurityLevel;
			Model.instance.query(sql);
				
			return Model.instance.data[0]['num'];
			
		}
		private function _getContactsBySql(sql:String):Array
		{
			if(Model.instance.query(sql))var result:Array = Model.instance.data;
			var resultAry:Array = new Array();
			for( var i:int=0;i<result.length; i++ )
				resultAry.push(new Contact(result[i]));
			return resultAry;
		}
		/**
		 * 添加联系人
		 */
		public function addContact(name:String, contact:String,d:int, t:int, sl:int ):Boolean
		{
			var sql:String = "INSERT INTO contacts (name,content,dept_id,type_id,security_level) values "
				+'("'+name+'","'+contact+'",'+d+','+t+','+sl+')';
			return Model.instance.query(sql);
		}

			
	}
}